import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Select, Tag } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import type { Gender, TableListItem } from './data';
import { queryMemberUserList } from './service';
import { GenderOptions, GenderParse } from './utils';

const TableList: React.FC = () => {
  const [sorter, setSorter] = useState<string>('');
  const actionRef = useRef<ActionType>();

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '昵称',
            dataIndex: 'nickname',
      render: (_, record) => <div>{record.nickname}</div>,
    },
    {
      title: '联系方式',
            dataIndex: 'phone',
      hideInSearch: true,
      render: (_, record) => <div>{record.phone || '未知'}</div>,
    },
    {
      title: '性别',
            dataIndex: 'gender',
      hideInSearch: true,
      render: (_, record) => {
        const gender: Gender = GenderParse.parse(record.gender);
        return <Tag color={gender.color}>{gender.name}</Tag>;
      },
      renderFormItem: (_, { onChange }) => (
        <Select defaultValue="0">
          {GenderOptions.map((item) => (
            <Select.Option key={item.id} value={item.id}>
              {item.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      title: '注册时间',
            dataIndex: 'registerDate',
      hideInSearch: true,
      render: (_, record) => <Tag>{record.registerDateTime || '未知'}</Tag>,
    },
    {
      title: '车牌',
            dataIndex: 'plateNumber',
      hideInSearch: true,
      render: (_, record) => <div>{record.plateNumber || '未知'}</div>,
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: true }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        params={{
          sorter,
        }}
        toolBarRender={() => []}
        tableAlertRender={() => false}
        rowSelection={false}
        request={(params = {}) => {
          const { current: page, pageSize, ...filter } = params;
          return queryMemberUserList({ page, pageSize, ...filter });
        }}
        columns={columns}
      />
    </PageHeaderWrapper>
  );
};

export default TableList;
